package com.sdgakj.service.orderFlow;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.sdgakj.dto.CreateOrderDTO;
import com.sdgakj.dto.OrderDTO;
import com.sdgakj.dto.base.ResCode;
import com.sdgakj.entity.Donation;
import com.sdgakj.entity.Order;
import com.sdgakj.entity.OrderPay;
import com.sdgakj.enums.EnumIsPay;
import com.sdgakj.enums.EnumOrderStatus;
import com.sdgakj.repository.*;
import com.sdgakj.service.ServiceException;
import com.sdgakj.service.order.OrderService;
import com.sdgakj.service.user.UserService;
import com.sdgakj.utils.SchoolSearchFilter;
import com.sdgakj.utils.SchoolSpecifications;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.sdgakj.entity.OrderFlow;
import org.springside.modules.mapper.BeanMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;

@Component
@Transactional
public class DonationService
{
	private static Logger logger = LoggerFactory.getLogger(OrderService.class);
	@Autowired
	private DonationDao donationDao;
	@Autowired
    private OrderFlowDao orderFlowDao;
	/*@Autowired
	private OrderDao orderDao;*/
	@Autowired
	private OrderPayDao orderPayDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserService userService;

	public List<Donation> getAllLis() {
		return (List<Donation>) donationDao.findAll();
	}

	public Donation getDonationById(Long id){
		return donationDao.findOne(id);
	}

	/*public Donation getDonationByGpsService(Long id){
		return donationDao.findByService(id);
	}
	public Order getOrderByGpsService(Long id) {
		return orderDao.findByService(id);
	}*/

	/**
	 * 保存
	 *
	 * @param entity
	 */

	public Donation saveDonation(Donation entity) {
		Timestamp tsc = new Timestamp(new Date().getTime());
		entity.setCreatetime(tsc);
		return donationDao.save(entity);
	}


	/**
	 * 保存
	 */
	public CreateOrderDTO create(Long userId,
								 String authTel,
								 Double totalPrice,
								 Integer realNum,
								 Integer targetNum) {
		CreateOrderDTO result = new CreateOrderDTO();
		if (0l == userId) {
			throw new ServiceException(ResCode.NEED_USERID);
		}
		Order order = new Order();
		order.setUserId(userId);
		order.setAuthTel(authTel);
		order.setState(EnumOrderStatus.DELETE.getCode());
		order.setAmount(totalPrice);
		order.setRealNum(realNum);
		order.setTargetNum(targetNum);
	//	Order newOrder = this.saveOrder(order);
	//	result.setCreateTime(newOrder.getCreatetime().getTime());
		//result.setOrderId(newOrder.getId());
		return result;
	}
    /*
    * 创建订单
    * */
/*
    public  void insertOrder(Order)
*/

	/**
	 * 更新
	 *
	 * @param entity
	 */
	public void updateDonation(Donation entity) {

		entity.setUpdatetime(new Date());

		donationDao.save(entity);
	}


	public Page<Donation> getOrderByPages(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortName, String sortType) {
		PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, Sort.Direction.DESC, "id");
		//searchParams.put("NOTEQ_state", 0);
		Map<String, SchoolSearchFilter> filters = SchoolSearchFilter.parse(searchParams);
		Specification<Donation> spec = SchoolSpecifications.bySearchFilter(filters.values(), Donation.class);
		return donationDao.findAll(spec, pageRequest);
	}

	/*
     * 获取我的订单 赵哲
     */
	/*public List<OrderDTO> getOrderByUserId(Long customorId, Integer type, Integer state) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("EQ_customor.id", customorId);
		searchParams.put("EQ_type", type);
		searchParams.put("EQ_state", state);
		Specification<Order> spec = buildSpecification(searchParams);
		Sort sort = new Sort(Direction.DESC, "id");
		List<Order> orders = orderDao.findAll(spec, sort);
		List<OrderDTO> orderDTOs = new ArrayList<OrderDTO>();
		for (Order order : orders) {
			closeNeedCloseOrder(order);
			if (!EnumOrderStatus.NEEDPAY.getCode().equals(order.getState())) {
				continue;
			}
			OrderDTO orderDTO = BeanMapper.map(order, OrderDTO.class);
			orderDTOs.add(orderDTO);
		}
		for (Order order : orders) {
			if (EnumOrderStatus.NEEDPAY.getCode().equals(order.getState())) {
				continue;
			}
			OrderDTO orderDTO = BeanMapper.map(order, OrderDTO.class);

			orderDTOs.add(orderDTO);
		}
		return orderDTOs;
	}*/

	/*
     * 获取待打款订单 赵哲
     */
	public Map<String, Object> payedBillNotify(String jsonData) throws JSONException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String resMsg = "请求成功";
		if (StringUtils.isBlank(jsonData)) {
			resMsg = "数据传输错误";
			resultMap.put("resMsg", resMsg);
			resultMap.put("resCode", "0");
			return resultMap;
		}

		org.json.JSONObject jsonObject = new org.json.JSONObject(jsonData);
		int resCode = jsonObject.getInt("resCode");
		if (resCode != 1) {
			resultMap.put("resMsg", "请求不正确");
			resultMap.put("resCode", "0");
			return resultMap;
		}


		org.json.JSONArray jsonArray = jsonObject.getJSONArray("data");
		int iSize = jsonArray.length();
		for (int i = 0; i < iSize; i++) {
			org.json.JSONObject jsonObj = jsonArray.getJSONObject(i);
			String id = String.valueOf(jsonObj.get("id"));
			String amount = String.valueOf(jsonObj.get("amount"));
			String state = String.valueOf(jsonObj.get("state"));
			String errMsg = String.valueOf(jsonObj.get("errMsg"));
		} //end for
		return resultMap;
	}


	// 订单支付返回结果
	public String orderPayResultNotify(HttpServletRequest request, HttpServletResponse response,
									   Map<String, Object> body, Integer payType) {

		String tradeStatus = (String) body.get("trade_status");
		String tradeNo = (String) body.get("trade_no");
		Long orderId = Long.valueOf((String) body.get("out_order_id"));
		String account = (String) body.get("account");
		/*Order order = this.getOrderById(orderId);*/

		/*Preconditions.checkNotNull(order,"订单Id为空orderId=" + orderId);*/

		JSONObject json = new JSONObject();
		if ("TRADE_FAIL".equals(tradeStatus)) {
			// 支付失败
			json.put("resCode", ResCode.PAY_ORDER_FAILED.resCode);
			json.put("resMsg", ResCode.PAY_ORDER_FAILED.resMsg);
		}
		if ("TRADE_SUCCESS".equals(tradeStatus)) {
        /*    if (2 == order.getIsPay()) {
                json.put("resCode", ResCode.PAY_ORDER_ALREADYPAY.resCode);
                json.put("resMsg", ResCode.PAY_ORDER_ALREADYPAY.resMsg);
                return json.toJSONString();
            }*/

			try {

				// 标志已经支付
				OrderPay orderPay = new OrderPay();
				//start--2016年7月29日14:55:29 李贺刚
				//logger.info(order.getId() + "payType:" + payType + "account:" + account + "tradeNo:" + tradeNo);
				//end--
				orderPay.setType(payType);
				orderPay.setAccount(account);
				orderPay.setTransactionNo(tradeNo);
				orderPay.setState(EnumIsPay.IsPay.getCode());
				orderPay.setPayTime(new Date());
				OrderPay newOrderPay = orderPayDao.save(orderPay);

				/*order.setOrderPay(newOrderPay);
				this.updateOrder(order);*/
				json.put("resCode", "0");
				json.put("resMsg", "订单支付成功");
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			}
		}

		return json.toJSONString();
	}

	// 订单支付返回结果
	/*public void closeNeedCloseOrder(Order order) {
		long currentTime = System.currentTimeMillis();
		// 在这个基础上减去24小时：
		Long courseCancelTime = currentTime - 24 * 60 * 60 * 1000;
		// 格式化时间，获取到的就是当前时间24小时之后的时间
		Date courseCancelDate = new Date(courseCancelTime);
		if (order.getState().equals(EnumOrderStatus.NEEDPAY.getCode())
				&& order.getCreatetime().before(courseCancelDate)) {
			// 订单创建时间在24小时之前，修改订单状态
			order.setState(EnumOrderStatus.CLOSED.getCode());
			this.updateOrder(order);
		}
	}*/

	/*
     * 订单取消退款
     */
	/*public void unrefundOrder(Long orderId) {
		Order order = this.getOrderById(orderId);
		order.setState(EnumOrderStatus.ISPAY.getCode());
		try {
			this.updateOrder(order);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}*/
	/*
     * 订单取消
     */
/*	public void cancelOrder(Long orderId) {
		Order order = this.getOrderById(orderId);
		order.setState(EnumOrderStatus.CLOSED.getCode());

		try {
			this.updateOrder(order);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}*/

	/*
     * 订单删除
     */
/*	public void deleteOrder(Long orderId) {
		Order order = this.getOrderById(orderId);
		order.setState(EnumOrderStatus.DELETE.getCode());

		try {
			this.updateOrder(order);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}*/

	/*
     * 获取订单价格
     */
/*	public Double getOrderPrice(Long orderId) {
		Order order = this.getOrderById(orderId);
		return order.getAmount();
	}*/

	/*
     * 订单投诉
     */
	public void complainOrder(Long orderId, String reason) {
		// Order order = this.getOrderById(orderId);

	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		}
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Order> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SchoolSearchFilter> filters = SchoolSearchFilter.parse(searchParams);
		Specification<Order> spec = SchoolSpecifications.bySearchFilter(filters.values(), Order.class);
		return spec;
	}

/*	public int getCountByWait() {

		return donationDao.getCountByWait();
	}*/


    public List<OrderFlow> getAllList()
    {
        return (List<OrderFlow>) orderFlowDao.findAll();
	}

    public OrderFlow getOrderFlowById(Long id)
    {
        return orderFlowDao.findOne(id);
	}
	
	/**
	 * 保存
	 * @param entity
	 */
    public void saveOrderFlow(OrderFlow entity)
    {
        orderFlowDao.save(entity);
	}
	
	/**
	 * 更新
	 * @param entity
	 */
    public void updateOrderFlow(OrderFlow entity)
    {
        orderFlowDao.save(entity);
	}

 /*   public Page<OrderFlow> getOrderFlowByPage(Map<String, Object> searchParams,
            int pageNumber, int pageSize, String sortType)
    {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
        Specification<OrderFlow> spec = buildSpecification(searchParams);
        return orderFlowDao.findAll(spec, pageRequest);
	}	*/
	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageReques(int pageNumber, int pagzSize,String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		}
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
/*
    private Specification<OrderFlow> buildSpecification(Map<String, Object> searchParams)
    {
        Map<String, SchoolSearchFilter> filters = SchoolSearchFilter.parse(searchParams);
        Specification<OrderFlow> spec = SchoolSpecifications.bySearchFilter(filters.values(),
                OrderFlow.class);
		return spec;
	}
*/

}
